package cn.puge.usercenter.shiro.realms;


import cn.puge.commonutils.R;
import cn.puge.usercenter.entity.PugeUserLogin;
import cn.puge.usercenter.service.PugeUserLoginService;
import cn.puge.usercenter.shiro.salt.MyByteSource;
import cn.puge.usercenter.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

/**
 * @author LIJW
 * 自定义realm
 * @date 2020/9/4 20:55
 */

public class CustomerRealm extends AuthorizingRealm {

    //处理授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    //处理认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("=============");
        //获取用户名
        String principal = (String) authenticationToken.getPrincipal();
        //在工厂中获取service对象
        PugeUserLoginService userLoginService = (PugeUserLoginService) ApplicationContextUtils.getBean("userLoginService");
        PugeUserLogin pugeUserLogin = userLoginService.getUserLogin(principal);

        if (!StringUtils.isEmpty(pugeUserLogin)){
            //返回数据库中信息
            return new SimpleAuthenticationInfo(pugeUserLogin.getUsername(),pugeUserLogin.getPassword(),new MyByteSource(pugeUserLogin.getSalt()),this.getName());
        }
        return null;
    }
}
